package me.zk.practice1.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: zhang kai
 * @Date: 2021/12/22
 * @Description:
 */
public class ReenterLockDemo {
    public static void main(String[] args) {
        Phone2 p = new Phone2();
        Phone2 p1 = new Phone2();
        new Thread(() -> p.sendCms(), "t1").start();
        new Thread(() -> p1.sendEmail(), "t2").start();

        while ( Thread.activeCount() > 2) {

        }
    }
}
class Phone {
    public synchronized void sendCms() {
        System.out.println(Thread.currentThread().getName() + "cms");
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        sendEmail();
    }

    public synchronized void sendEmail() {
        System.out.println(Thread.currentThread().getName() + "email");
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
class Phone2 {
    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void sendCms() {

        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "cms");
            TimeUnit.SECONDS.sleep(1);
            sendEmail();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void sendEmail() {
        try {
            lock.lock();
            System.out.println(Thread.currentThread().getName() + "email");
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}